package org.oims.simpleserver.msg;


import com.alibaba.fastjson.JSON;
import org.oims.simpleserver.endpoint.EndpointArbiter;
import org.oims.simpleserver.entities.msg.SimpleMsg;
import org.oims.simpleserver.exceptions.ClientOfflineException;
import org.oims.simpleserver.utils.SpringUtils;

import java.io.IOException;

/**
 * 消息推送器，同步
 */
public class MsgNotifier {
    //默认的重试次数
    private static final int DEFAULT_RETRY_NUM = 4;
    private static final EndpointArbiter endpointArbiter = SpringUtils.getBean(EndpointArbiter.class);

    public static void sendMsg(String id, SimpleMsg msg) throws IOException, ClientOfflineException {
        String jsonStr = JSON.toJSONString(msg);
        for (int i = 0; i < DEFAULT_RETRY_NUM; i++) {
            try {
                endpointArbiter.pushMsg(id, jsonStr);
                return;
            } catch (ClientOfflineException e) {
                throw e;
            } catch (Exception e) {
                //如果最后一次还是失败了，再抛出异常
                if (i + 1 == DEFAULT_RETRY_NUM) {
                    throw e;
                }
            }
        }
    }
}
